package com.oceantrader.sale.commons.vertx;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.hazelcast.config.Config;

import io.vertx.core.Vertx;
import io.vertx.core.spi.cluster.ClusterManager;
import io.vertx.spi.cluster.hazelcast.HazelcastClusterManager;

/**
 * Vertx配置
 * 
 * @author xuesinuo
 */
@Configuration
public class VertxConfiguration {
    @Bean
    public Vertx vertx() throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(1);
        final Vertx[] vertxRef = new Vertx[1];

        Config hazelcastConfig = new Config();
        ClusterManager mgr = new HazelcastClusterManager(hazelcastConfig);
        Vertx.builder()
                .withClusterManager(mgr)
                .buildClustered()
                .onSuccess(vertx -> {
                    vertxRef[0] = vertx;
                    latch.countDown();
                });
        if (!latch.await(10, TimeUnit.SECONDS)) {
            throw new RuntimeException("Timed out waiting for clustered Vertx initialization");
        }
        return vertxRef[0];
    }
}
